#include "instanceholder.h"
#include <QMetaProperty>

InstanceHolder::InstanceHolder(LibLoader *loader) :
    QObject(0)
{
    this->loader = loader;
}

InstanceHolder::InstanceHolder(LibLoader *loader, QScriptEngine *sEng) :
    QObject(0)
{
    this->loader = loader;
    this->sEngine = sEng;
}

QObject* InstanceHolder::getObject(const QString &id, const QString &className, const QString &libName)
{
    if (this->objTable.contains(id))
    {
        return this->objTable.value(id);
    }

    QObject* obj = this->loader->getClassInstance(className, libName);
    if (obj)
    {
        const QMetaObject *metaObject = obj->metaObject();
        metaObject->property(metaObject->indexOfProperty("id")).write(obj, id);
//        QVariant mv = metaObject->property(metaObject->indexOfProperty("enums")).read(obj);
//        if (!mv.isNull()) {
//            QMap<QString, QVariant> m = mv.toMap();
//            QMapIterator<QString, QVariant> i(m);
//            while (i.hasNext()) {
//                sEngine->globalObject().setProperty(i.key(), i.value().toInt(), QScriptValue::ReadOnly);
//            }
//        }
        this->objTable.insert(id, obj);
        if (this->sEngine) {
            QScriptValue v = sEngine->newQObject(obj);
            this->sEngine->globalObject().setProperty(id, v);
        }
    }

    return obj;
}

void InstanceHolder::destroyObject(const QString &id)
{
    QObject* obj = this->objTable.value(id);
    if (obj)
    {
        this->objTable.remove(id);
        //        if (sEngine)
        //        {
        //            sEngine->property()
        //        }
        delete obj;
    }
}

void InstanceHolder::destroyAll()
{
    QHash<QString, QObject*>::const_iterator i = this->objTable.begin();
    while (i != this->objTable.end()) {
        QObject* obj = i.value();
        delete obj;
        i++;
    }
}

/*
 * TODO: this metod is only a working template
 * should improve it on further development
 * FIXME: will enter endless loop when object DB
 * already contains id's:
 * object0 ... object<MAX_UNSIGNED>
 */
QString InstanceHolder::createUniqId() const
{
    static unsigned int objCount = 0;
    QString result = QString("anonymous%1").arg(objCount);
    while ( objTable.keys().contains(result) )
        result = QString("anonymous%1").arg(++objCount);
    return result;
}

InstanceHolder::~InstanceHolder()
{
    destroyAll();
}
